package com.atguigu.gmall.mq.receiver;

import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class ConfirmReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    //  监听刚刚发送的消息.
    //  1.  初始化：交换机，路由键，队列。 2.  监听消息.
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue.confirm",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "exchange.confirm"),
            key = {"routing.confirm"}
    ))
    public void getMsg(String msg, Message message, Channel channel) throws IOException {
        try {
            System.out.println("msg:\t"+msg);
            //  int i = 1/0;
            System.out.println("message:\t"+new String(message.getBody()));

        } catch (Exception e) {
            //  第三个重回队列.
            //  int index = 3; 放入redis set index 3;
            //            for (int i = 0; i <=3; i++) {
            //                //  index --; set index
            //                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            //            }
            //  借助redis 来判断重回队列的次数！ 如果到了次数之后，还没有正确消费！ 将它放入消息记录表 insert into tname values ();
            //  记录消息结构.
            System.out.println("消费签收失败.");
            //  throw new RuntimeException(e);
        }
        //  手动确认: 第一个参数相当于消息标签; 第二个参数：判断是否是批量确认true，还是单个确认;false
        //  如果没有确认：消息会一直在队列中.
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        System.out.println("消费签收成功.");
    }

    //  监听消息.
    @SneakyThrows
    @RabbitListener(queues = DeadLetterMqConfig.queue_dead_2)
    public void dead2(String msg,Message message, Channel channel){
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            System.out.println("接收的消息:\t"+msg+"\t"+simpleDateFormat.format(new Date()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听消息.
    @SneakyThrows
    @RabbitListener(queues = DelayedMqConfig.queue_delay_1)
    public void delay(String msg,Message message, Channel channel){
        String uuid = "";
        try {
            //  消费这个消息之前，判断这个消息是否被消费过?  redis ---> setnx： key'不存在的情况下生效.
            uuid = (String) message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
            System.out.println(uuid);
            Boolean result = redisTemplate.opsForValue().setIfAbsent(uuid+":lock", uuid, 10, TimeUnit.SECONDS);
            if (result){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println("接收的消息:\t"+msg+"\t"+simpleDateFormat.format(new Date()));
            } else {
                System.out.println("没有执行成功.");
            }

        } catch (Exception e) {
            //  分布式：考虑lua脚本.
            this.redisTemplate.delete(uuid);
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
